﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using AuditModel;
using System.Text.RegularExpressions;
using System.Data;
using AuditWeb.Models;
using System.Reflection;
using System.Drawing;
using DoddleReport.Web;
using DoddleReport;

namespace AuditWeb.Controllers
{
    public class AdminController : Controller
    {
        //
        // GET: /Admin/
        IAnnualEventBL aebl = new AnnualEventBL();
        IArchiveBL abl = new ArchiveBL();
        private AuditDBEntities db = new AuditDBEntities();
        ICandidateQuotaBL icqbl = new CandidateQuotaBL();
        IScoreBL isbl = new ScoreBL();

        [Authorize(Roles = "管理员")]
        public ActionResult ScoreLogs(string subjectid, string serialnumber, string archiveid)
        {
            AnnualEvent currentevent = aebl.GetActiveEvents().FirstOrDefault();
            string annualeventid = currentevent.ID;
            ViewBag.AnnualEvent = currentevent;
            ViewBag.AnnualEventId = annualeventid;
            ViewBag.SelectedIndex = "5";

            int _subjectid;
            int.TryParse(subjectid, out _subjectid);
            _subjectid = _subjectid <= 0 ? -1 : _subjectid;
            serialnumber = string.IsNullOrEmpty(serialnumber) ? "" : serialnumber;
            archiveid = string.IsNullOrEmpty(archiveid) ? "" : archiveid;

            //var scorelogs = from s in db.Scores where s.Archive.AnnualEventID == annualeventid select s;
            var scorelogs = isbl.GetScores(annualeventid,_subjectid, serialnumber, archiveid);
            ViewBag.SubjectID = new SelectList(Helpers.GetActiveSubjects(annualeventid), "ID", "Name", subjectid);
            ViewBag.SerialNumber = serialnumber;
            ViewBag.ArchiveID = archiveid;
            ViewBag.Subject = subjectid;
            //[10:01:30] jibach: IScoreBL.GetScores(int subjectID,string expertSerialNumber,string archiveID)

            return View(scorelogs);
        }

      
        
        [Authorize(Roles = "管理员")]
        public ActionResult Index()
        {
            AnnualEvent ae = aebl.GetActiveEvents().First();
            ViewBag.AnnualEvent = ae;
            ViewBag.AnnualEventId = ae.ID;

            //SubjectCount of AnnualEvent
            var cqlist=icqbl.GetCandidateQuotas(ae.ID, -1, "");
            int SubjectCount = (from cq in cqlist select new { cq.SubjectID }).Distinct().Count();
            ViewBag.SubjectCount = SubjectCount;
            //CountyCount of AnnualEvent
            int CountyCount = (from cq in cqlist select new { cq.CountyCode }).Distinct().Count();
            ViewBag.CountyCount = CountyCount;
            //ExpertJudgeCount of AnnualEvent
            int ExpertJudgeCount = (from ej in db.ExpertJudges where ej.AnnualEventID == ae.ID select ej).Count();
            ViewBag.ExpertJudgeCount = ExpertJudgeCount;
            //ArchivesCount, CandidateQuota
            int ArchivesCount = (from a in db.Archives where a.AnnualEventID == ae.ID select a).Count();
            ViewBag.ArchivesCount = ArchivesCount;
            ViewBag.CandidateQuota = cqlist.Sum(sp => sp.Quota);
            
            //ScoreCount per Subject
            //List<AuditModel.sp_GetSubjectsProgressReport_Result>
            ViewBag.ScoreProgress = icqbl.GetSubjectProgressReport(ae.ID);


            return View();

        }
        [Authorize(Roles = "管理员")]
        public ActionResult ScorePercentages()
        {
            AnnualEvent currentevent = aebl.GetActiveEvents().FirstOrDefault();
            string annualeventid = currentevent.ID;

            var scorepercentages = from sp in db.ScorePercentages where sp.AnnualEventID == annualeventid select sp;
            ViewBag.AnnualEvent = currentevent;
            ViewBag.AnnualEventId = annualeventid;
            ViewBag.SelectedIndex = "4";
            return View(scorepercentages);
        }
        [Authorize(Roles = "管理员")]
        public ActionResult CandidateStatistics(string countycode, string subjectid)
        {
            AnnualEvent currentevent = aebl.GetActiveEvents().FirstOrDefault();
            string annualeventid = currentevent.ID;
            ViewBag.AnnualEvent = currentevent;
            ViewBag.AnnualEventId = annualeventid;
            ViewBag.SelectedIndex = "5";
            int _subjectid;
            int.TryParse(subjectid, out _subjectid);
            _subjectid = _subjectid <= 0 ? -1 : _subjectid;
            countycode = countycode == null ? "" : countycode.Trim();

            var qlist = icqbl.GetCandidateQuotasTotal(annualeventid, _subjectid, countycode).ToList();
            //actural archives count
            ViewBag.ArchivesCount = qlist.Sum(sp => sp.Total);
            ViewBag.CandidateQuota = qlist.Sum(sp => sp.Quota);
            //Cadidate statistics for grid
            ViewBag.CandidateStatistics = qlist;
            AdminArchiveModel aam = new AdminArchiveModel() { AnnualEventId = annualeventid, CountyCode = countycode, SubjctId = _subjectid };

            ViewBag.CountyCode = new SelectList(db.Counties.ToList(), "Code", "Name", countycode);
            ViewBag.SubjectId = new SelectList(Helpers.GetActiveSubjects(annualeventid), "Id", "Name", _subjectid);
            return View(aam);
        }
        [Authorize(Roles = "管理员")]
        public ActionResult Archives(string countycode, string subjectid, string archiveid)
        {
            AnnualEvent currentevent = aebl.GetActiveEvents().FirstOrDefault();
            string annualeventid = currentevent.ID;

            countycode = countycode == null ? "" : countycode.Trim();
            int _subjectid;
            int.TryParse(subjectid, out _subjectid);
            _subjectid = _subjectid <= 0 ? -1 : _subjectid;
            archiveid = archiveid == null ? "" : archiveid.Trim();
            AdminArchiveModel aam = new AdminArchiveModel() { AnnualEventId = annualeventid, CountyCode = countycode, ArchiveId = archiveid, SubjctId = _subjectid, Date=DateTime.Now.Date };

            var archives = abl.GetArchives(annualeventid, archiveid, _subjectid, countycode);//db.Archives.Include("AnnualEvent").Include("Subject").Include("County").Include("Teacher");
            ViewBag.AnnualEvent = currentevent;
            ViewBag.AnnualEventId = annualeventid;
            ViewBag.Archives = archives.ToList();
            ViewBag.SelectedIndex = "3";
            ViewBag.CountyCode = new SelectList(db.Counties.ToList(),"Code","Name", countycode);
            ViewBag.SubjectId = new SelectList(Helpers.GetActiveSubjects(annualeventid),"Id","Name", _subjectid);

            return View(aam);
        }
        [Authorize(Roles = "管理员")]
        public ActionResult DeleteArchive(string id,string countycode,string subjectid, string archiveid,string targetarchiveid)
        {
            Archive archive=db.Archives.SingleOrDefault(a=>a.ID==targetarchiveid);
            db.Archives.DeleteObject(archive);
            db.SaveChanges();

            return RedirectToAction("Archives", new { id = id, countycode = countycode, subjectid = subjectid, archiveid = archiveid });
        }

        [HttpPost]
        [Authorize(Roles = "管理员")]
        public ActionResult SetDate(AdminArchiveModel aam)
        {
            if (ModelState.IsValid)
            {
                string annualeventid = aam.AnnualEventId;
                string s = Request.Form.ToString();
                string[] nv = s.Split('&');
                //string datetype = Request.Form["DateType"];
                //DateTime date = DateTime.Parse(Request.Form["Date"]);
                foreach (string ss in nv)
                {
                    string archiveid = ss.Split('=')[0];
                    string v = ss.Split('=')[1];
                    if (v == "true")
                    {
                        Archive archive = db.Archives.SingleOrDefault(a => a.ID == archiveid);
                        if (archive != null)
                        {
                            switch (aam.DateType)
                            {
                                case "0":
                                    archive.ClassDate = aam.Date;
                                    if (aam.Date != archive.EvaluationStartDate)
                                    {
                                        archive.EvaluationStartDate = aam.Date;
                                        archive.EvaluationDueDate = aam.Date.AddDays(2);
                                    }
                                    break;
                                case "1":
                                    archive.EvaluationStartDate = aam.Date;
                                    if (aam.Date > archive.EvaluationDueDate)
                                        archive.EvaluationDueDate = aam.Date.AddDays(2);
                                    break;
                                case "2":
                                    if(aam.Date>=archive.EvaluationStartDate)
                                        archive.EvaluationDueDate = aam.Date;
                                    break;
                                case "3":
                                    archive.ClassTime = aam.Date;
                                    break;
                                default:
                                    break;
                            }
                            //db.Archives.Attach(archive);
                            db.ObjectStateManager.ChangeObjectState(archive, EntityState.Modified);
                            db.SaveChanges();
                        }
                    }
                }
            }

            return RedirectToAction("Archives", new { id = aam.AnnualEventId, archiveid=aam.ArchiveId, countycode=aam.CountyCode, subjectid=aam.SubjctId });
        }

        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }
    }
}
